<template>
    <h-section title="业务需求及其关联产品需求" collapse :defaultOpen="!!form.pmpRequestInfos.length" class="relate-require-list-wrap">
        <a-table
            rowKey="id"
            bordered
            size="small"
            :columns="tableColumns"
            :data-source="form.pmpRequestInfos"
            :expandedRowKeys="expandedRowKeys"
            :pagination="false"
            @expand="onHandleExpand"
        >
            <template #level="{ record }">
                <h-level :level="record.level" v-if="record.level" />
            </template>
            <template #action="{ record }">
                <div style="display: inline-block" v-if="!disabled && stepStatus !== 'requireOnline'">
                    <a @click="handleCreate(record)" v-auth="'version.versionList.addRequire'">新建产品需求</a>
                    <a-divider type="vertical" v-auth="'version.versionList.addRequire'" />
                </div>
                <a @click="showDetail(record)">详情</a>
                <!-- 待开始或者需求基线才可以删除 -->
                <div
                    style="display: inline-block"
                    v-if="!disabled && (!record?.pmpProductRequires || !(record?.pmpProductRequires && record?.pmpProductRequires.length))"
                >
                    <a-divider type="vertical" />
                    <a @click="handleBeforeRemoveTask(record.id)">移除</a>
                </div>
            </template>
            <!-- 产品需求 -->
            <template #expandedRowRender="{ record }">
                <product-table v-bind="$props" :list="record.pmpProductRequires" @deleteHandle="handleDelete">
                    <template #title>
                        <div class="font-w-b" style="padding: 0 0 8px 0px">受理信息</div>
                        <!-- background: #fff; -->
                        <div
                            style="padding: 8px 0px 8px 8px; margin-left: -8px; min-height: 32px; white-space: pre-wrap"
                            v-html="record.auditOpinion"
                        />
                    </template>
                </product-table>
            </template>
        </a-table>
        <a-modal title="需求调整原因" centered v-model:visible="visible" :width="800">
            <a-textarea placeholder="请输入需求调整原因限制300个字" showCount :maxlength="300" auto-size v-model:value="changeOpinion" />
            <template #footer>
                <flexbox justify="flex-end" class="btn-group">
                    <a-button type="primary" @click="handleOk">提交</a-button>
                </flexbox>
            </template>
        </a-modal>

        <a-modal title="需求调整原因" centered v-model:visible="taskVisible" :width="800">
            <a-textarea placeholder="请输入需求调整原因限制300个字" showCount :maxlength="300" auto-size v-model:value="changeOpinion" />
            <template #footer>
                <flexbox justify="flex-end" class="btn-group">
                    <a-button type="primary" @click="handleRemoveTask">提交</a-button>
                </flexbox>
            </template>
        </a-modal>

        <!-- 创建产品需求 -->
        <CreateStory ref="createStoryRef" :detail="detail" @success="onHandleCreateProSuccess" />
    </h-section>
</template>

<script lang="ts">
import filters from '@/utils/filter';
import CreateStory from '@/views/taskRequire/taskDetail/components/CreateStory.vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { HLevel } from '@/components';
import ProductTable from './productTable.vue';
import { useRouter } from 'vue-router';
import api from '@/api';
import store from '@/store';
import { message } from 'ant-design-vue';
import { defineComponent, reactive, toRefs, watch, ref, unref } from 'vue';
export default defineComponent({
    name: 'RelateRequireList',
    components: {
        HLevel,
        ProductTable,
        PlusOutlined,
        CreateStory
    },
    props: {
        detail: { type: Object, default: () => ({}) },
        disabled: { type: Boolean, default: false },
        stepStatus: { type: String, default: '' },
        hasAuth: { type: Boolean, default: false }
    },
    emits: ['success'],
    setup(props, { emit }) {
        const router = useRouter();
        const createStoryRef = ref<any>();
        const state = reactive<any>({
            form: {
                pmpRequestInfos: []
            },
            changeOpinion: '',
            productRequireId: '',
            visible: false,
            taskVisible: false, //业务需求弹窗是否线索
            businessId: '',
            currSelectRequestRecord: {}, // 当前选中的业务需求
            expandedRowKeys: []
        });
        const tableColumns = [
            {
                title: '业务需求名称',
                dataIndex: 'requestName',
                ellipsis: true
            },
            {
                title: '开发周期(天)',
                dataIndex: 'devCycle',
                width: 150
            },
            {
                title: '费用(元)',
                dataIndex: 'cost',
                width: 150
            },
            {
                title: '发起人',
                dataIndex: 'initiator',
                width: 150
            },
            {
                title: '发起部门',
                dataIndex: 'initiatorDept',
                width: 150
            },
            {
                title: '操作',
                dataIndex: '',
                key: 'action',
                slots: { customRender: 'action' },
                align: 'center',
                width: 200
            }
        ];
        const showDetail = (info: any) => {
            const { id } = info;
            router.push({
                path: '/taskRequire/taskDetail',
                query: {
                    id
                }
            });
        };
        const handleOk = async () => {
            if (state.visible === true && !state.changeOpinion) {
                message.error('调整原因不能为空');
                return;
            }
            state.visible = false;
            const { id, versionName, versionNumber, processStatus } = props.detail;
            const { empId, name } = store.getters.userInfo.employeeDTO;
            const query = {
                productRequireId: state.productRequireId,
                relateVersionId: id,
                relateVersionName: versionName,
                relateVersionNumber: versionNumber,
                status: 'delete',
                record: ['3', '4', '5', '6', '7', '8', '9'].includes(processStatus), // 789(验收，上线审核和上线流程)需要记录需求列表操作
                empId,
                empName: name,
                processStatus,
                taskNode: props.stepStatus,
                changeOpinion: state.changeOpinion
            };
            const { success, errorMsg } = await api.productRequireModel.batchDeal([query]);
            if (success) {
                state.changeOpinion = '';
                message.success('操作成功');
                emit('success');
            } else {
                message.error(errorMsg);
            }
        };
        // 移除产品需求
        const handleDelete = async (productRequireId: number) => {
            state.productRequireId = productRequireId;
            if (props.detail.pmpProductRequires.length === 1 && props.stepStatus === 'requireOnline') {
                message.warn('这是该版本唯一的需求，不可移除');
                return;
            }
            if (+props.detail.processStatus >= 3) {
                state.visible = true;
                state.changeOpinion = '';
            } else {
                handleOk();
            }
        };
        // 移除无产品需求的业务需求
        const handleBeforeRemoveTask = async (id: number) => {
            state.businessId = id;
            if (+props.detail.processStatus >= 3) {
                state.taskVisible = true;
                state.changeOpinion = '';
            } else {
                handleRemoveTask();
            }
        };
        const handleRemoveTask = async () => {
            if (state.taskVisible === true && !state.changeOpinion) {
                message.error('调整原因不能为空');
                return;
            }
            state.taskVisible = false;
            const { id } = props.detail;
            const query = {
                businessId: state.businessId,
                versionId: id,
                type: 'delete',
                taskNode: props.stepStatus,
                changeOpinion: state.changeOpinion
            };
            const { success, errorMsg } = await api.pmpRequestInfoModel.signpostBVSave(query);
            if (success) {
                state.changeOpinion = '';
                message.success('操作成功');
                emit('success');
            } else {
                message.error(errorMsg);
            }
        };
        // 创建产品需求回调
        const onHandleCreateProSuccess = () => {
            const index = state.expandedRowKeys.indexOf(state.currSelectRequestRecord.id);
            if (index == -1) {
                state.expandedRowKeys.push(state.currSelectRequestRecord.id);
            }
            state.currSelectRequestRecord = {};
            emit('success');
        };
        const handleSave = async (index: number) => {
            const query = {
                ...state.form.pmpRequestInfos[index]
            };
            const { success } = await api.pmpRequestInfoModel.updateBusiness(query);
            if (success) {
                message.success('操作成功');
            }
        };
        const handleClear = (index: number) => {
            state.form.pmpRequestInfos[index].verOpinion = '';
            handleSave(index);
        };
        // 业务需求下新建产品需求
        const handleCreate = async (record) => {
            state.currSelectRequestRecord = { ...record };
            const { requestName, requestDesc: requireDesc, id, requestSystem, source } = record;
            const { pmpProductDetailDTO, id: relateVersionId, versionName: relateVersionName, versionNumber: relateVersionNumber } = props.detail;
            // 找出该系统默认的当前处理人
            const { success, moule } = await api.systemManagerModel.findManagersBySystem({
                catalogCode: pmpProductDetailDTO.catalogCode,
                position: '产品经理'
            });
            if (success) {
                // 自动填写默认值，需求类型，优先级，需求描述，所属系统，关联业务需求等
                let target = moule.find((item) => item.empId === store.getters.userInfo.employeeDTO.empId);
                target = target || moule[0];
                unref(createStoryRef).open({
                    requireName: requestName,
                    requireDesc,
                    requireType: filters.valToNameFilter('source', source) === '缺陷' ? '4' : '1',
                    level: '4',
                    agentUser: target.empName,
                    agentUserEmpId: target.empId,
                    relateRequireId: id,
                    relateRequireName: requestName,
                    requireSystem: +requestSystem,
                    devType: pmpProductDetailDTO.systemType !== '3' ? pmpProductDetailDTO.systemType : '2',
                    systemType: pmpProductDetailDTO.systemType,
                    // 关联版本信息
                    relateVersionId,
                    relateVersionName,
                    relateVersionNumber
                });
            }
        };
        // 表格展开回调事件
        const onHandleExpand = (expanded, record) => {
            if (expanded) {
                state.expandedRowKeys.push(record.id);
            } else {
                const index = state.expandedRowKeys.indexOf(record.id);
                if (index > -1) {
                    //如果出现则截取这个id,1d到1相当于0，针对重复点击一个
                    state.expandedRowKeys.splice(index, 1);
                }
            }
        };
        const init = () => {
            state.form.pmpRequestInfos = props.detail.pmpRequestInfos ? props.detail.pmpRequestInfos : [];
        };
        init();
        watch(() => props.detail, init, { deep: true });
        return {
            createStoryRef,
            ...toRefs(state),
            tableColumns,
            showDetail,
            handleDelete,
            handleSave,
            handleClear,
            handleOk,
            handleBeforeRemoveTask,
            handleRemoveTask,
            handleCreate,
            onHandleCreateProSuccess,
            onHandleExpand
        };
    }
});
</script>
<style lang="less" scoped>
.flow-text {
    margin-bottom: 8px;
    a {
        font-size: 14px;
        margin-left: 8px;
    }
}
.relate-require-list-wrap {
    ::v-deep(.ant-table) {
        background: transparent !important;
    }
    // table的title背景色
    ::v-deep(.ant-table-title) {
        background: #f8f8f9;
        border: none;
        margin: 0;
        padding: 12px 0 8px 8px;
    }
    ::v-deep(.ant-table-body) {
        .ant-table-body {
            .ant-table-thead > tr > th {
                background: #f8f8f9 !important;
                font-weight: bold;
            }
            .ant-table-tbody {
                background: #f8f8f9 !important;
            }
        }
    }
    ::v-deep(tr.ant-table-expanded-row) {
        & > td:first-child {
            border-right: none !important;
        }
    }
    .canEdit {
        cursor: pointer;
        color: @primary-color;
    }
    .disabledEdit {
        cursor: not-allowed;
        color: @disable-font-color;
    }
    .opinion-cont {
        white-space: pre-wrap;
        color: @error-color;
    }
}
</style>